"""
诗词卡片生成脚本
功能：每日自动生成包含动态诗词、金句、二维码和logo的卡片
依赖库：pip install Pillow qrcode schedule
"""

import os
import json
import qrcode
import schedule
import time
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont

# =================配置区（用户修改部分）=================
CONFIG = {
    "card_size": (1000, 1500),          # 卡片尺寸(宽,高)
    "bg_color": "#FAF3E0",              # 背景颜色
    "text_color": "#2C2C2C",            # 正文颜色
    "highlight_color": "#B03A2E",        # 金句颜色
    "font_path": "SourceHanSerifCN-Light.ttf",  # 中文字体文件路径
    "logo_path": "logo.png",             # Logo文件路径
    "output_dir": "daily_cards",        # 输出目录
    "qrcode_url": "https://example.com/poem/{date}",  # 动态二维码链接
    "data_file": "poetry_data.json"      # 诗词数据文件
}

# 元素位置配置（单位：像素）
LAYOUT = {
    "logo": (50, 50),
    "title": (500, 200),
    "content": (500, 300),
    "highlight": (500, 800),
    "qrcode": (700, 1200)
}

# =================功能实现部分=================
class PoetryCardGenerator:
    def __init__(self, config):
        self.config = config
        self._validate_paths()
        
        # 创建输出目录
        os.makedirs(config['output_dir'], exist_ok=True)

    def _validate_paths(self):
        """验证必要文件是否存在"""
        required_files = ['font_path', 'logo_path', 'data_file']
        for key in required_files:
            if not os.path.exists(self.config[key]):
                raise FileNotFoundError(f"缺失必要文件：{self.config[key]}")

    def _load_data(self):
        """加载诗词数据"""
        with open(self.config['data_file'], 'r', encoding='utf-8') as f:
            data = json.load(f)
        today = datetime.now().strftime("%Y-%m-%d")
        return data.get(today, data["default"])

    def _generate_qrcode(self, url):
        """生成动态二维码"""
        qr = qrcode.QRCode(
            version=2,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=8,
            border=4
        )
        qr.add_data(url)
        qr.make(fit=True)
        return qr.make_image(fill_color="#3A3845", back_color="white")

    def generate_card(self):
        """生成当日卡片"""
        # 加载数据
        data = self._load_data()
        
        # 创建画布
        card = Image.new("RGB", self.config['card_size'], self.config['bg_color'])
        draw = ImageDraw.Draw(card)
        
        # 添加Logo
        logo = Image.open(self.config['logo_path']).resize((200, 200))
        card.paste(logo, LAYOUT['logo'])
        
        # 设置字体
        title_font = ImageFont.truetype(self.config['font_path'], 42)
        content_font = ImageFont.truetype(self.config['font_path'], 32)
        highlight_font = ImageFont.truetype(self.config['font_path'], 36)
        
        # 排版文本
        text_elements = [
            (data['title'], LAYOUT['title'], title_font, self.config['text_color']),
            (data['content'], LAYOUT['content'], content_font, self.config['text_color']),
            (data['highlight'], LAYOUT['highlight'], highlight_font, self.config['highlight_color'])
        ]
        
        # 绘制文本
        for text, position, font, color in text_elements:
            draw.text(position, text, font=font, fill=color, anchor="mm")
        
        # 添加动态二维码
        date_str = datetime.now().strftime("%Y%m%d")
        qr_url = self.config['qrcode_url'].format(date=date_str)
        qr_img = self._generate_qrcode(qr_url)
        card.paste(qr_img, LAYOUT['qrcode'])
        
        # 保存文件
        output_path = os.path.join(
            self.config['output_dir'],
            f"card_{datetime.now().strftime('%Y%m%d')}.png"
        )
        card.save(output_path)
        print(f"已生成当日卡片：{output_path}")

# =================定时任务=================
def job():
    try:
        generator = PoetryCardGenerator(CONFIG)
        generator.generate_card()
    except Exception as e:
        print(f"卡片生成失败：{str(e)}")

if __name__ == "__main__":
    # 立即生成一次
    job()
    
    # 设置每日00:00自动执行
    schedule.every().day.at("00:00").do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(60)

"""
诗词数据文件示例（poetry_data.json）：
{
  "default": {
    "title": "默认诗名",
    "content": "默认诗词内容",
    "highlight": "默认金句"
  },
  "2024-03-20": {
    "title": "春晓",
    "content": "春眠不觉晓\n处处闻啼鸟\n夜来风雨声\n花落知多少",
    "highlight": "春意盎然万物苏"
  }
}
"""
